<?php

namespace App\Http\Services\Message;

use App\Exceptions\MessageException;
use App\Models\ChatRoom;
use App\Models\ChatRoomMember;
use App\Models\ChatRoomMessage;
use App\Models\Member;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MessageService {

    public static function chatRoomList(Request $request,$memberId)
    {
        $data = $request->all();

        $perPage = intval($request->input('per_page',10));
        //var_dump('$memberId',$memberId);
        $model = ChatRoom::query()
            ->whereHas('chat_room_member',function($q)use($memberId){
                $q->where('member_id',$memberId);
            });

        if (!empty($data['key_word']))
        {
            $model->where(function($q)use($data,$memberId){
                $q->where(function($q)use($data,$memberId){
                    $q->whereHas('chat_room_member_opposite',function($q)use($data,$memberId){
                        $q->where('member_id','!=',$memberId);
                        $q->whereHas('member',function($q)use($data){
                            $q->where('nick_name','like','%' . $data['key_word']. '%');
                        });
                    });
                });
                $q->orWhere(function($q)use($data){
                    $q->whereHas('chat_room_message',function($q)use($data){
                        $q->where('message','like','%' . $data['key_word']. '%');
                    });
                });

            });
//            $model->whereHas('chat_room_member_opposite',function($q)use($data,$memberId){
//                $q->where('member_id','!=',$memberId);
//                $q->whereHas('member',function($q)use($data){
//                    $q->where('nick_name','like','%' . $data['key_word']. '%');
//                });
//            });
        }

        $model->with(['chat_room_member_opposite' => function($q)use($memberId){
            $q->where('member_id','!=',$memberId);
            $q->with(['member' => function($q){
                $q->select(["id","nick_name","profile_photo"]);
            }]);
        }]);

        $model->with(['chat_room_member_me' => function($q)use($memberId){
            $q->where('member_id','=',$memberId);
        }]);

        $model->with(['chat_room_last_message' => function($q){
            $q->with(["from_member" => function($q){
                $q->select(["id","nick_name","profile_photo"]);
            }]);
            $q->with(["to_member" => function($q){
                $q->select(["id","nick_name","profile_photo"]);
            }]);
        }]);

        $res = $model
                ->orderBy('updated_at','desc')
                ->paginate($perPage);

        $res = $res->toArray();
        unset($res['links']);

        return $res;
    }

    public static function chatRoomMessageList(Request $request, $memberId)
    {

        $toMemberId = $request->to_member_id;
        $chatId = $request->chat_id;
        $toMember = Member::query()->select(["id","nick_name","profile_photo"])->findOrFail($toMemberId)->toArray();
        if (empty($request->chat_id))
        {
            $chatRoom = ChatRoom::query()
                    ->whereHas('chat_room_member',function($q)use($memberId){
                        $q->where('member_id',$memberId);
                    })
                    ->whereHas('chat_room_member',function($q)use($toMemberId){
                        $q->where('member_id',$toMemberId);
                    })
                    ->orderBy('created_at','desc')
                    ->first();
            if (!$chatRoom)
            {
                return [
                    'data' => [],
                    'to_member' => $toMember,
                ];
            }
            $chatId = $chatRoom->id;
        }

        $myChatRoomMember = ChatRoomMember::query()
            ->where([
                ['chat_room_id',$chatId],
                ['member_id',$memberId],
            ])
            ->first();

        $oppositeChatRoomMember = ChatRoomMember::query()
            ->where([
                ['chat_room_id',$chatId],
                ['member_id','!=',$memberId],
            ])
            ->with(["member" => function($q){
                $q->select(["id","nick_name","profile_photo"]);
            }])
            ->first();

        // 将聊天标记为已读
        if (!empty($myChatRoomMember->is_new_to_read))
        {
            $myChatRoomMember->is_new_to_read = 0;
            $myChatRoomMember->save();
        }

        $perPage = intval($request->input('per_page',10));

        $model = ChatRoomMessage::query()
            ->whereHas('chat_room',function($q)use($memberId){
                $q->whereHas('chat_room_member',function($q)use($memberId){
                    $q->where('member_id',$memberId);
                });
            });
        if (!empty($data['key_word']))
        {
            $model->where('message','like','%' . $data['key_word']. '%');
        }
        $model->where('chat_room_id',$chatId);

        $model->with(["from_member" => function($q){
            $q->select(["id","nick_name","profile_photo"]);
        }]);
        $model->with(["to_member" => function($q){
            $q->select(["id","nick_name","profile_photo"]);
        }]);

        $model->with(["is_send" => function($q)use($memberId){
            $q->where('id',$memberId);
            $q->select(["id"]);
        }]);

        $res = $model->orderBy('created_at','desc')
            ->paginate($perPage);

        $res = $res->toArray();
        unset($res['links']);

        $res['opposite_member'] = $oppositeChatRoomMember->toArray();
        $res['to_member'] = $toMember;
        $res['data'] = array_reverse($res['data']);

        return $res;
    }

    public static function sendMessage($memberId,$toMemberId,$msg)
    {

        $toMember = Member::query()->findOrFail($toMemberId);

        $chatRoom = ChatRoom::query()
            ->whereHas('chat_room_member',function($q)use($memberId,$toMemberId){
                $q->where('member_id',$memberId);
            })
            ->whereHas('chat_room_member',function($q)use($memberId,$toMemberId){
                $q->where('member_id',$toMemberId);
            })
            ->first();

        try{
            DB::beginTransaction();

            if (!$chatRoom)
            {
                $chatRoom = ChatRoom::saveEntity([
                    'chat_room_name' =>  $memberId . '_' . $toMemberId,
                ]);

                ChatRoomMember::query()->insert([
                    [
                        'chat_room_id' => $chatRoom->id,
                        'member_id' => $memberId,
                        'created_at' => date('Y-m-d H:i:s')
                    ],
                    [
                        'chat_room_id' => $chatRoom->id,
                        'member_id' => $toMemberId,
                        'created_at' => date('Y-m-d H:i:s')
                    ],
                ]);
            }

            $chatRoomToMember = ChatRoomMember::query()
                ->where([
                    ['chat_room_id',$chatRoom->id],
                    ['member_id',$toMemberId],
                ])
                ->first();

            if (!$chatRoomToMember)
            {
                throw new MessageException("消息发送对象不存在.");
            }

            $sendMessage = [
                'chat_room_id'   => $chatRoom->id,
                'from_member_id' => $memberId,
                'to_member_id'   => $toMember->id,
                'message'        => $msg,
                'created_at'     => date('Y-m-d H:i:s'),
            ];

            // 将聊天发送对象标记为未读
            if (empty($chatRoomToMember->is_new_to_read))
            {
                $chatRoomToMember->is_new_to_read = 1;
                $chatRoomToMember->save();
            }

            // 更新聊天室最近更新时间
            $chatRoom->updated_at = date('Y-m-d H:i:s');
            $chatRoom->save();

            $res = ChatRoomMessage::saveEntity($sendMessage);

            DB::commit();

            return $res;

        }catch(\Exception $e){
            DB::rollBack();
            return false;
        }
    }


    public static function unreadChatCount($memberId)
    {
        $myUnReadChatRoomMemberCount = ChatRoomMember::query()
            ->where([
                ['member_id',$memberId],
                ['is_new_to_read',1],
            ])
            ->count();

        return ['unread_chat_count' => $myUnReadChatRoomMemberCount];
    }

    public static function readAllChat($memberId)
    {
        ChatRoomMember::query()
            ->where([
                ['member_id',$memberId],
                ['is_new_to_read',1],
            ])
            ->update([
                'is_new_to_read' => 0,
                'updated_at'     => date('Y-m-d H:i:s'),
            ]);

        return true;
    }


}